package com.frame.database.util;

import java.io.Serializable;
import java.sql.*;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate4.SessionFactoryUtils;

import com.frame.database.TableKey;
import com.frame.hibernate.HibernateUtil;
import com.wframe.framework.spring.SpringContextHolder;

/**
 * @Title: 系统
 * @Description:
 * @Copyright: Copyright (c) 2012
 * @Company:
 * @author 王海锋
 * @CreatedTime:2012-5-14 下午04:52:40
 * @version 1.0
 */

public class Seq {
    public static final String KEYGEN="key_generator";
    public Connection conn;
    private boolean closed=false;
    public Seq(){

    }
    public Seq(Connection conn){
        this.conn=conn;
    }
    public Serializable getKeyId(String name){
        return getKeyId(name,"integer",10);
    }
    public Serializable getKeyId(TableKey keyColumn){
        return getKeyId(keyColumn.getTableName().toUpperCase()+"_ID",keyColumn.getType(),keyColumn.getLength());
    }
    public Serializable getKeyId(String name,String type,int length){
        ResultSet rs=null;
        Statement st =null;
        Serializable next=1;
        boolean close=false;
        Session session=null;
        try {
            if(conn==null || closed){
//                session=HibernateUtil.openSession();
                conn=SessionFactoryUtils.getDataSource((SessionFactory)SpringContextHolder.getBean("sessionFactory")).getConnection();
                conn.setAutoCommit(true);
                close=true;
            }
            st=conn.createStatement();
            rs = st.executeQuery("select STARTNUM from "+KEYGEN+" where keyname ='"+name+"'");
            if ( rs.next() ) {
                int l=rs.getInt(1);
                try{
                    st.addBatch("update "+KEYGEN+" set STARTNUM="+(l+1)+" where keyname ='"+name+"'");
                    st.executeBatch();
                    next = getValue(l,type,length);
//                    conn.commit();
                }catch(Exception ws){System.out.println("生成主键id失败！");ws.printStackTrace();}
            }
            else {
                try{
                    st.executeUpdate("insert into "+KEYGEN+"(keyname,STARTNUM,length,type) values('"+name+"',2,"+length+",'"+type+"')");
                    next=getValue(1,type,length);
//                    conn.commit();
                }catch(Exception ww){
                    System.out.println("生成主键id失败！插入主键表key_generator字段"+name+"失败");
                    ww.printStackTrace();
                }
            }
//            Transaction trans=HibernateUtil.currentSession().getTransaction();
//            if(trans!=null && trans.isActive())
//                HibernateUtil.currentSession().beginTransaction();
        }catch(Exception e) {
            throw new HibernateException(e);
        }
        finally {
            try{
                if(rs!=null)
                    rs.close();
            }catch(SQLException e)
            {
            }
            try{
                if(st!=null)
                    st.close();
            }catch(SQLException e)
            {
            }
            if(close){
                try {
                    if(session!=null)
                        session.close();
                } catch (Exception e) {
                }
                try {
                    conn.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                closed=true;
            }
        }
        return next;
    }
    public String getKeySeqName(TableKey keyColumn){
        return keyColumn.getTableName().toUpperCase()+"_ID";
    }
    private Serializable getValue(int v,String keytype,int length) throws Exception{
        if(keytype.equalsIgnoreCase("integer"))
            return new Integer(v);
        else if(keytype.equalsIgnoreCase("string")){
            String value=String.valueOf(v);
            String str="";
            for(int i=0;i<length-value.length();i++){
                str+="0";
            }
            return str+value;
        }
        else{
            return null;
        }
    }
}
